<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               :upload-before="uploadBefore"
               ref="crud"
               @row-dblclick="handleRowDBLClick"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @sort-change="sortChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   effect="dark"
                   v-if="permission.wa_api_task_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-divider direction="vertical" />
      </template>

      <template #deviceType="{ row }">
        <el-tag effect="dark">{{ row.$deviceType }}</el-tag>
      </template>
      <template #isCheck="{ row }">
        <el-tag :type="type.yes_no[row.isCheck]" effect="dark">{{ row.$isCheck }}</el-tag>
      </template>
      <template #isRealDevice="{ row }">
        <el-tag :type="type.yes_no[row.isRealDevice]" effect="dark">{{ row.$isRealDevice }}</el-tag>
      </template>
      <template #status="{ row }">
        <el-tag :type="type.enable_disable[row.status]" effect="dark">{{ row.$status }}</el-tag>
      </template>
    </avue-crud>

    <el-dialog
      v-model="apiTaskBox"
      append-to-body
      destroy-on-close
      draggable
      title="号码列表"
      width="80%"
      align-center>
      <apiPhone ref="apiPhoneRef" :api-task-id="apiTaskId"></apiPhone>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/whatsapp/api-task';
import option from '@/option/whatsapp/api-task';
import { mapGetters } from 'vuex';
import func from '@/utils/func';
import type from '@/const/tag/type';
import apiPhone from '@/views/whatsapp/api-phone.vue';

export default {
  data() {
    return {
      apiTaskBox: false,
      apiTaskId: undefined,
      form: {},
      query: {},
      sort: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: []
    };
  },
  components: {
    apiPhone
  },
  computed: {
    type() {
      return type;
    },
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.wa_api_task_add, false),
        viewBtn: this.validData(this.permission.wa_api_task_view, false),
        delBtn: this.validData(this.permission.wa_api_task_delete, false),
        editBtn: this.validData(this.permission.wa_api_task_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    this.sort.descs = 'create_time';
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    sortChange(val) {
      this.sort = {};
      if (func.notEmpty(val.order)) {
        if (val.order === 'ascending') {
          this.sort.ascs = func.cameCaseToLine(val.prop);
        } else {
          this.sort.descs = func.cameCaseToLine(val.prop);
        }
      }
      this.refreshChange();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        taskName,
        deviceType,
        isRealDevice,
        createTime,
        status
      } = Object.assign(params, this.query);

      let values = {
        taskName_like: taskName,
        deviceType_equal: deviceType,
        isRealDevice_equal: isRealDevice,
        createTime_datege: createTime ? createTime[0] : undefined,
        createTime_datelt: createTime ? createTime[1] : undefined,
        status_equal: status
      };

      getList(page.currentPage, page.pageSize, this.sort, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    uploadBefore(file, done, loading) {
      loading();
      const reader = new FileReader();
      reader.readAsText(file);
      reader.onload = (e) => {
        let num = 0;
        const result = e.target.result;
        // 数据校验
        if (func.isEmpty(result.trim())) {
          this.$message.error('文本无数据,请仔细核对');
          return;
        }
        const data = result.split('\n');
        if (data.length > 100000) {
          this.$message.error('超出单次任务上传数量!');
          return;
        }
        const substrings = ['|', '----'];
        for (const key in data) {
          num++;
          let row = data[key].trim();
          if (func.notEmpty(row)) {
            let containsAny = substrings.some(sub => row.includes(sub));
            console.info(data[key]);
            console.info(containsAny);
            if (!containsAny) {
              this.$message({ showClose: true, message: '第' + num + '行格式错误! 请核对后在上传', type: 'error', duration: 10000 });
              return;
            }
          }
        }

        done();
      };
    },
    handleRowDBLClick(row, event){
      this.apiTaskId = row.id;
      this.apiTaskBox = true;
    },
  }
};
</script>

<style>
</style>
